//
//  MYGAcademicConferenceLiverInteractVC.swift
//  MYDoctor
//
//  Created by Denny on 2024/5/27.
//

import UIKit
import JXSegmentedView
import IQKeyboardManagerSwift
class MYGAcademicConferenceLiverInteractVC: MYGBaseController ,JXSegmentedListContainerViewListDelegate {
    
    var meeting_id = ""
    var commentModels = [MYGTopicCommentModel]()
    private var isHot:Bool = true
    
    var contents:[MYGAcademicCommentCellModel] = []
    func listView() -> UIView {
        return self.view
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enable = false
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = true
    }
    var line: UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(hexString: "eeeeee")
        return control
    }()
   
   
    
    lazy var hotBtn:UIButton = {
        let control = UIButton()
        control.setTitle("最热", for: .normal)
        control.titleLabel?.font = .regular(12)
        control.setBackgroundColor(color: UIColor.init(hexString: "#3B37DE").withAlphaComponent(0.12), forState: .selected)
        control.setBackgroundColor(color: .white, forState: .normal)
        control.setTitleColor(UIColor.init(hexString: "#3B37DE"), for: .selected)
        control.setTitleColor(UIColor.init(hexString: "#868686"), for: .normal)
        control.addCorner(conrners: .allCorners, radius: 12, boradColor: UIColor.init(hexString: "E3E3E3"), boradWidth: 0.5)
        control.addTarget(self, action: #selector(exchangeType(_:)), for: .touchUpInside)

        control.tag = 50
        control.isSelected = true
        return control
    }()
    
    lazy var newBtn:UIButton = {
        let control = UIButton()
        control.setTitle("最新", for: .normal)
        control.titleLabel?.font = .regular(12)
        control.setBackgroundColor(color: UIColor.init(hexString: "#3B37DE").withAlphaComponent(0.12), forState: .selected)
        control.setBackgroundColor(color: .white, forState: .normal)
        control.setTitleColor(UIColor.init(hexString: "#3B37DE"), for: .selected)
        control.setTitleColor(UIColor.init(hexString: "#868686"), for: .normal)
        control.addCorner(conrners: .allCorners, radius: 12, boradColor: UIColor.init(hexString: "E3E3E3"), boradWidth: 0.5)
        control.tag = 51
        control.addTarget(self, action: #selector(exchangeType(_:)), for: .touchUpInside)
        return control
    }()

    lazy var tableView: UITableView = {
        let control = UITableView.init(frame: .zero, style: .plain)
        control.showsVerticalScrollIndicator = false
        control.delegate = self
        control.dataSource = self
//        control.estimatedRowHeight = 170
//        control.rowHeight = UITableView.automaticDimension
        control.separatorStyle = .none
//        control.ww_foldable = true
        control.register(cellWithClass: MYGAcademicCommentCell.self)
        return control
    }()
    
  
    @objc func exchangeType(_ sender:UIButton) {
        sender.isSelected = !sender.isSelected
        if sender == hotBtn {
            hotBtn.isSelected = true
            newBtn.isSelected = false
            isHot = true
        }else {
            newBtn.isSelected = true
            hotBtn.isSelected = false
            isHot = false
        }
        dataFactory()
    }
   
    deinit{
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        addSubViews()
        view.backgroundColor = .white
        NotificationCenter.default.addObserver(self, selector: #selector(dataFactory), name: NSNotification.Name("MYGAcafemicCommentList"), object: nil)

        dataFactory()
    }

   
    func addSubViews() {
        
        view.backgroundColor = .white
        view.addSubview(line)
        line.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(1)
        }
        
        view.addSubview(hotBtn)
        hotBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize.init(width: 55, height: 24))
            make.left.equalToSuperview().offset(21)
            make.top.equalToSuperview().offset(15)
        }
        view.addSubview(newBtn)
        newBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize.init(width: 55, height: 24))
            make.left.equalTo(hotBtn.snp.right).offset(27.5)
            make.top.equalToSuperview().offset(15)
        }
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(hotBtn.snp.bottom).offset(10)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-40 - bottomSafeheight)
        }
        
    }
}

extension MYGAcademicConferenceLiverInteractVC {
    //评论
    func sendComment(_ text:String,model:MYGAcademicCommentCellModel) {
        var params:[String:Any] = [:]
        params["user_type"] = "1"
        params["data_id"] = meeting_id
        params["pid"] = model.id
        params["type"] = "9"
        params["content"] = text
        
        MYGLoading.show()
        MYGNetwork<MYGMeAPI, MYGTopicCommentModel>.request(target: .commentSubmit(param:params)) { [self] item in
            MYGLoading.hide()
            
//            let comment = item
//            comment.reply = [MYGTopicCommentModel]()
//            comment.doctor.name = MYGUserManager.getUser()?.doctor.name ?? ""
//            comment.doctor.avatar = MYGUserManager.getUser()?.doctor.avatar ?? ""
//            self.commentModels.append(comment)
            
            dataFactory()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    //点赞
    private func tapLike(model:MYGAcademicCommentCellModel) {
        var params:[String:Any] = [:]
        params["like_status"] = model.isLike == 1 ? "0" : "1"
        params["id"] = model.id
        MYGLoading.show()
        MYGNetwork<MYGMeAPI, MYGEmptyModel>.request(target: .commentLike(param: params)) { [self] item in
            MYGLoading.hide()
            if model.isLike == 1 {
                model.isLike = 0
                model.likeCount = model.likeCount - 1
            }else {
                model.isLike = 1
                model.likeCount = model.likeCount + 1
            }
            tableView.reloadData()
       } failed: { _, error in
           MYGLoading.hide()
           MMYGHUD.showToast(text: error)
       }
    }
    
    
   @objc private func dataFactory(){
        self.contents.removeAll()
        
        MYGLoading.show()
        var params:[String:Any] = [:]
        params["data_id"] = meeting_id
        params["type"] = "9"
        params["is_new"] = isHot ? "0" : "1"
        params["is_heat"] = isHot ? "1" : "0"
        
        MYGNetwork<MYGMeAPI, MYGPageModel<MYGTopicCommentModel>>.request(target: .commentCommentList(param: params)) { item in
            MYGLoading.hide()
            self.commentModels = item.list

            item.list.forEach { model in
                guard let commands = model.reply, commands.count > 0 else {
                    // 无评论
                    let cellModel = MYGAcademicCommentCellModel(id:model.id,avar: model.doctor.avatar, name: model.doctor.name, time: model.created_at, content: model.comment, isLike: model.is_like, likeCount: model.likes, models: [], cellHeight: 0.0)
                    self.contents.append(cellModel)
                    return
                }
                //有评论 评论cell内容宽度 screenWidth - 205 cell的top为11
                var commentSubHeight:CGFloat = 20
                commands.forEach { obj in
                    let size = getStringSize(font: .regular(12), viewSize: CGSize(width: screenWidth - 205 , height: CGFLOAT_MAX), str: obj.comment)
                    commentSubHeight = commentSubHeight + size.height + 11
                }
                print(commentSubHeight)
                let cellModel = MYGAcademicCommentCellModel(id:model.id,avar: model.doctor.avatar, name: model.doctor.name, time: model.created_at, content: model.comment, isLike: model.is_like, likeCount: model.likes, models: commands, cellHeight: commentSubHeight)
                self.contents.append(cellModel)
            }

            self.tableView.reloadData()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }

    }
}

extension MYGAcademicConferenceLiverInteractVC: UITableViewDataSource,UITableViewDelegate {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: MYGAcademicCommentCell.self)
        let model = self.contents[indexPath.row]
        cell.model = model
        cell.likeBlock = {[self] in
            self.tapLike(model: model)
        }
        cell.answerBlock = {[self] in

            let alert = UIAlertController(title: "提示", message: "请输入评论内容", preferredStyle: .alert)
            alert.addTextField { tf in
                tf.placeholder = "请输入评论内容"
            }
            
            let okey = UIAlertAction(title: "确定", style: .default) { _ in
                alert.dismiss(animated: true)
                guard let text = alert.textFields?.first?.text, !text.isEmpty else {
                    return
                }
                
                self.sendComment(text, model: model)
            }
            
            let cancel = UIAlertAction(title: "取消", style: .cancel)
            alert.addAction(okey)
            alert.addAction(cancel)
            
            self.present(alert, animated: true)
            
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.contents.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = self.contents[indexPath.row]
        return model.cellHeight + 125 + 20
    }
}
